/*
 * @Date         : 2024-05-20 11:11:09 星期1
 * @Author       : xut
 * @Description  :
 */
import { resolve } from "node:path"
import * as grpc from "@grpc/grpc-js"
import * as protoLoader from "@grpc/proto-loader"
import { ProtoGrpcType } from "../pb/index.services"
import { envConfig } from "../server/config/default"

const options: protoLoader.Options = {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
}

const PORT = envConfig.port
const serverUrl = `localhost:${PORT}`
const PROTO_FILE = "../proto/index.services.proto"
const insecure = grpc.credentials.createInsecure()

const packageDef = protoLoader.loadSync(resolve(__dirname, PROTO_FILE), options)
export const proto = grpc.loadPackageDefinition(
  packageDef
) as unknown as ProtoGrpcType

export const authClient = new proto.auth.AuthService(serverUrl, insecure)

export const userClient = new proto.user.UserService(serverUrl, insecure)

export const postClient = new proto.post.PostService(serverUrl, insecure)

const deadline = new Date()
deadline.setSeconds(deadline.getSeconds() + 5)

const clients = [authClient, userClient, postClient]
let clientReadyCount = 0

clients.forEach((client) => {
  client.waitForReady(deadline, (err: any) => {
    if (err) {
      console.error(err)
      return
    }
    onClientReady()
  })
})
function onClientReady() {
  clientReadyCount++

  if (clientReadyCount === clients.length) {
    console.log("🚀 gRPC All Client is ready: ", clientReadyCount)
  }
}
